package com.cwm.test.flyweight.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;

public class ConnectionPool {
    private CopyOnWriteArrayList<Connection> pool;
    private CopyOnWriteArrayList<Connection> busyPool;

    private int poolSize = 10;
    private String url = "jdbc:mysql://localhost:3306/test";
    private String userName = "root";
    private String password = "123456";
    private String driverClassName = "com.mysql.cj.jdbc.Driver";


    public ConnectionPool() {
        pool = new CopyOnWriteArrayList<Connection>(new ArrayList<>(poolSize));
        busyPool = new CopyOnWriteArrayList<Connection>();
        try {
            Class.forName(driverClassName);
            for (int i = 0; i < poolSize; i++) {
                Connection conn = DriverManager.getConnection(url, userName, password);
                pool.add(conn);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            busyPool.add(conn);
            System.out.println("拿到了连接！");
            return conn;
        }
        System.out.println("连接已满！请等待连接释放");
        return null;
    }

    public void release(Connection conn) {
        pool.add(conn);
        busyPool.remove(conn);
    }

    public void releaseOne() {
        pool.add(busyPool.get(0));
        busyPool.remove(0);
        System.out.println("释放了一个连接");
    }

    public int size() {
        return pool.size();
    }

    public int busySize() {
        return busyPool.size();
    }


}
